<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools :num="total">
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >导入excel</el-button>
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="hExportExcel"
        >导出excel</el-button>
        <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <!-- 1.定义需要根据字段排序的字段名称 :default-sort="{prop: 'xxxx'}" -->
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column type="index" :index="getIndex" label="序号" width="70" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像" width="125">
            <template v-slot="{row}">
              <!-- <img :src="row.staffPhoto" alt=""> -->
              <!-- {{ row.staffPhoto }} -->
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <!-- {{row.formOfEmployment === 1 ? '正式' : '非正式'}} -->
              {{ format(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <!-- 2.保证字段列上声明了prop属性 和 sortable属性 -->
          <el-table-column sortable prop="timeOfEntry" label="入职时间" width="150" />
          <!-- <el-table-column prop="" label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next"
            :current-page="page"
            :total="total"
            :page-size="size"
            :page-sizes="[5,10,15]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工的弹层 -->
    <el-dialog
      title="添加员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="$refs.empDialog.resetForm()"
    >
      <!-- <EmpDialog v-if="showDialog" @success="hSuccess" /> -->
      <EmpDialog ref="empDialog" @success="hSuccess" />
    </el-dialog>
    <!-- 分配角色的弹层 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <AssignRole
        v-if="showDialogRole"
        :cur-id="curId"
        @colseRole="showDialogRole = false"
        @colse="hSuccessRole"
      />
    </el-dialog>
  </div>
</template>

<script>
const TYPE_MAP = { 1: '正式', 2: '非正式', 3: 'AAA', 4: 'BBB', 5: 'CCC', 6: 'DDD' }
// import TYPE_MAP from '@/constant'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'

export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      curId: '', // 当前点击角色的id
      showDialog: false, // 添加员工
      showDialogRole: false, // 设置角色
      // 分页
      list: [],
      total: 0,
      page: 1,
      size: 5
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    // 子组件保存角色成功
    hSuccessRole() {
      // 1.关闭弹层
      this.showDialogRole = false
      // 2.提示用户
      this.$message.success('保存成功')
    },
    // 点击了分配角色
    hAssign(id) {
      this.showDialogRole = true
      // 保存id传给子
      this.curId = id
    },
    // 用来处理数据的函数
    formatData(rows) {
      // 表头（英文的表单需要转中文）
      const enHeader = Object.keys(rows[0])
      const mapObj = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const header = enHeader.map(en => mapObj[en])
      // 内容
      const data = rows.map(obj => {
        // 对应聘形式进行转换
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出Excel
    async hExportExcel() {
      // 1.发请求拿到员工信息
      const { data: res } = await getEmployeeList({ page: this.page, size: this.size })
      // console.log(res)
      // 2.对数据进行格式化转换
      const { header, data } = this.formatData(res.rows)
      // 3.导出
      console.log('员工信息', header, data)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        // 生成Excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    getIndex(index) {
      return index + (this.page - 1) * this.size + 1
    },
    // 子组件添加成功
    hSuccess() {
      // 1.关闭弹层
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.size)
      // 2.更新数据
      this.loadEmployee()
    },
    async doDel(id) {
      try {
        // 1.调删除接口
        await delEmployee(id)
        // 2.提示
        this.$message.success('删除员工成功')
        // 解决分页删除异常
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        // 3.刷新
        this.loadEmployee()
      } catch (e) {
        this.$message.error(e)
      }
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('确认要删除吗？', '系统提示')
        .then(() => {
        // 做删除
          this.doDel(id)
        }).catch(() => {})
    },
    // 点击页码时触发
    hCurrentChange(curPage) {
      console.log(`当前页: ${curPage}`)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployee()
    },
    // 更改每页多少条时触发
    hSizeChange(curPagesize) {
      console.log(`每页 ${curPagesize} 条`)
      this.size = curPagesize
      this.page = 1
      // 2. 重发请求
      this.loadEmployee()
    },
    // 格式化应聘形式
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    // 获取员工列表
    async loadEmployee() {
      const { data: res } = await getEmployeeList({ page: this.page, size: this.size })
      // console.log(res)
      this.list = res.rows
      this.total = res.total
    }
  }
}
</script>
